package com.xjrsoft.module.workflow.service.impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.core.secure.XjrUser;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.*;
import com.xjrsoft.module.base.dto.ModuleDto;
import com.xjrsoft.module.base.entity.XjrBaseModule;
import com.xjrsoft.module.base.entity.XjrBaseTempfield;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.service.IXjrBaseModuleService;
import com.xjrsoft.module.base.service.IXjrBaseTempfieldService;
import com.xjrsoft.module.base.service.IXjrBaseUserRelationService;
import com.xjrsoft.module.form.entity.XjrFormSchemeInfo;
import com.xjrsoft.module.form.service.IXjrFormSchemeInfoService;
import com.xjrsoft.module.workflow.dto.GetPageListNwfTaskDto;
import com.xjrsoft.module.workflow.dto.NwfRelationDto;
import com.xjrsoft.module.workflow.dto.NwfSchemeInfoDto;
import com.xjrsoft.module.workflow.dto.XjrNwfRelationDto;
import com.xjrsoft.module.workflow.entity.XjrNwfRelation;
import com.xjrsoft.module.workflow.entity.XjrNwfScheme;
import com.xjrsoft.module.workflow.entity.XjrNwfSchemeauth;
import com.xjrsoft.module.workflow.entity.XjrNwfSchemeinfo;
import com.xjrsoft.module.workflow.mapper.NwfSchemeInfoMapper;
import com.xjrsoft.module.workflow.service.IXjrNwfRelationService;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeAuthService;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeInfoService;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeService;
import com.xjrsoft.module.workflow.vo.NwfSchemeInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class XjrNwfSchemeInfoServiceImpl extends ServiceImpl<NwfSchemeInfoMapper, XjrNwfSchemeinfo> implements IXjrNwfSchemeInfoService {

    @Autowired
    private IXjrNwfSchemeService nwfSchemeService;
    @Autowired
    private IXjrNwfSchemeAuthService nwfSchemeAuthService;
    @Autowired
    private IXjrBaseTempfieldService tempfieldService;
    @Autowired
    private IXjrBaseUserRelationService xjrBaseUserRelationService;
    @Autowired
    private IXjrFormSchemeInfoService xjrFormSchemeInfoService;
    @Autowired
    private IXjrNwfRelationService nwfRelationService;
    @Autowired
    private IXjrBaseModuleService baseModuleService;

    @Autowired
    private  RepositoryService repositoryService;

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/26
     * @Param:[modelId]
     * @return:com.xjrsoft.module.workflow.entity.XjrNwfSchemeinfo
     * @Description:根据modelId查询
     */
    @Override
    public XjrNwfSchemeinfo getByModelId(String modelId) {
        QueryWrapper<XjrNwfSchemeinfo> queryWrapper = new QueryWrapper();
        queryWrapper.eq("F_modelId", modelId);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/7
     * @Param:[idValue]
     * @return:com.xjrsoft.module.workflow.entity.XjrNwfSchemeinfo
     * @Description:根据部署Id查询
     */
    @Override
    public XjrNwfSchemeinfo getByDeploymentId(String idValue) {
        QueryWrapper<XjrNwfSchemeinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(XjrNwfSchemeinfo::getDeploymentId, idValue);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/20
     * @Param:[]
     * @return:void
     * @Description:自定义分页查询
     */
    @Override
    public PageOutput<NwfSchemeInfoVo> selectDataPage(GetPageListNwfTaskDto dto) {
        JSONArray nwfSchemeInfoIds = StringUtils.isNotBlank(dto.getNwfSchemeInfoId()) ? JSON.parseArray(JSON.toJSONString(dto.getNwfSchemeInfoId().split(StringPool.COMMA))) : new JSONArray();
        Page<NwfSchemeInfoVo> page = baseMapper.selectNwfSchemeInfoPage(new Page(dto.getLimit(), dto.getSize()), dto.getKeyword(), dto.getFIsInapp(), dto.getCategory(), nwfSchemeInfoIds, dto.getMark());
        List<NwfSchemeInfoVo> nwfSchemeInfoVos = page.getRecords();
        List<String> schemeInfoIds = nwfSchemeInfoVos.stream().map(NwfSchemeInfoVo::getId).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(schemeInfoIds)) {
            List<XjrNwfSchemeauth> xjrNwfSchemeauthList = nwfSchemeAuthService.list(Wrappers.<XjrNwfSchemeauth>query().lambda().in(XjrNwfSchemeauth::getSchemeinfoId, schemeInfoIds));
            //权限
            //不为管理员
            XjrUser user = SecureUtil.getUser();
            if (!SecureUtil.isAdminUser()) {
                Iterator<NwfSchemeInfoVo> iterator = nwfSchemeInfoVos.iterator();
                while (iterator.hasNext()) {
                    NwfSchemeInfoVo nwfSchemeInfoVo = iterator.next();
                    List<XjrNwfSchemeauth> xjrNwfSchemeauths = xjrNwfSchemeauthList.stream().filter(x -> x.getSchemeinfoId().equals(nwfSchemeInfoVo.getId())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(xjrNwfSchemeauths)) {
                        boolean flag = false;
                        for (XjrNwfSchemeauth xjrNwfSchemeauth : xjrNwfSchemeauths) {
                            if (xjrNwfSchemeauth != null && xjrNwfSchemeauth.getObjType() != null) {
                                //如果权限为岗位
                                Integer objType = xjrNwfSchemeauth.getObjType();
                                if (objType == 1) {
                                    List<XjrBaseUser> xjrBaseUsers = xjrBaseUserRelationService.getUsersOfObject(xjrNwfSchemeauth.getObjId(), 2);
                                    Map<String, XjrBaseUser> xjrBaseUserMap = xjrBaseUsers.stream().collect(Collectors.toMap(s -> s.getUserId(), s -> s));
                                    if (xjrBaseUserMap.get(user.getUserId()) != null) {
                                        flag = true;
                                    }
                                }
                                //角色
                                if (objType == 2) {
                                    List<XjrBaseUser> xjrBaseUsers = xjrBaseUserRelationService.getUsersOfObject(xjrNwfSchemeauth.getObjId(), 1);
                                    Map<String, XjrBaseUser> xjrBaseUserMap = xjrBaseUsers.stream().collect(Collectors.toMap(s -> s.getUserId(), s -> s));
                                    if (xjrBaseUserMap.get(user.getUserId()) != null) {
                                        flag = true;
                                    }
                                }
                                //用户
                                if (objType == 3) {
                                    String userId = xjrNwfSchemeauth.getObjId();
                                    if (userId.equals(user.getUserId())) {
                                        flag = true;
                                    }
                                }
                                //所有
                                if (objType == 4) {
                                    flag = true;
                                }
                            }
                        }
                        if (!flag) {
                            iterator.remove();
                        }
                    } else {
                        iterator.remove();
                    }
                }
            }
        }
        return ConventPage.getPageOutput(page);
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/20
     * @Param:[]
     * @return:void
     * @Description:
     */
//    @Override
//    public List<NwfSchemeInfoVo> selectData(GetPageListNwfTaskDto dto) {
//        JSONArray nwfSchemeInfoIds = StringUtils.isNotBlank(dto.getNwfSchemeInfoId()) ? JSON.parseArray(JSON.toJSONString(dto.getNwfSchemeInfoId().split(StringPool.COMMA))) : new JSONArray();
//        Page<NwfSchemeInfoVo> page = baseMapper.selectNwfSchemeInfoPage(new Page(dto.getLimit() * dto.getSize() - dto.getSize(), dto.getSize()), dto.getKeyword(), dto.getFIsInapp(), dto.getCategory(), nwfSchemeInfoIds, dto.getMark());
//        return page.getRecords();
//    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/21
     * @Param:[fId:主键ID]
     * @return:boolean
     * @Description:根据主键删除流程模板
     */
    public boolean delete(String fId) {
        XjrNwfSchemeinfo xjrNwfSchemeinfo = getById(fId);
        return false;
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/26
     * @Param:[nwfSchemeInfoId, status]
     * @return:boolean
     * @Description:修改流程设计模板状态
     */
    @Override
    public boolean updateProcessStatus(String nwfSchemeInfoId, String status) {
        boolean flag = false;
        XjrNwfSchemeinfo xjrNwfSchemeinfo = getById(nwfSchemeInfoId);
        if (xjrNwfSchemeinfo != null) {
            xjrNwfSchemeinfo.setEnabledMark(Integer.valueOf(status));
            flag = updateById(xjrNwfSchemeinfo);
        }
        return flag;
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/20
     * @Param:[dto, currentUser]
     * @return:boolean
     * @Description:保存流程模板设计
     */
    @Transactional
    @Override
    public String saveProcess(NwfSchemeInfoDto dto, XjrUser currentUser) throws Exception {
        // 流程设计权限
        JSONArray jsonArray = JSON.parseArray(dto.getSchemeAuthList());
        // 流程图json
        String xml = dto.getXml();
        // 流程配置Json
        String json = dto.getJson();
        // 流程任务命名规则
//        String ruleName = dto.getRuleName();
        // 关联流程任务配置
//        JSONObject associatedTasks = dto.getAssociatedTasks();
        // 流程超时设置
//        JSONObject timeoutToRemind = dto.getTimeoutToRemind();
//         流程关联菜单
        JSONObject menu = dto.getMenu();
        // 流程模板实体类
        XjrNwfSchemeinfo xjrNwfSchemeinfo = BeanUtil.copy(dto, XjrNwfSchemeinfo.class);
        // 模板ID
        String modelId = xjrNwfSchemeinfo.getModelId();
        String schemeInfoId = StringUtil.randomUUID();
        JSONObject obj = JSONObject.parseObject(json);
        JSONArray childShapes = obj.getJSONArray("childShapes");
        if(CollectionUtil.isEmpty(childShapes)){
            throw new Exception("请添加节点事件");
        }
        boolean bind = JsonUtil.isBind(json, schemeInfoId);
        if (!bind) {
            throw new Exception("改表单已绑定其他流程,请重新选择其他表单!!");
        }
        // 流程字符串处理
        String newJson = JsonUtil.processJsonHandle(json, schemeInfoId);
        // 部署流程
        String deployId = FlowableUtil.deployByJson(modelId, newJson, xjrNwfSchemeinfo.getName(), currentUser.getUserId());
        // 获取版本号
        String version = FlowableUtil.getVersionByDepId(deployId);
        if (StringUtils.isNotBlank(deployId)) {
            // 流程模板ID
            String schemeId = StringUtil.randomUUID();
            // 流程模板信息id
            XjrNwfScheme newXjrNwfScheme = new XjrNwfScheme();
            // 流程模板的新增
            newXjrNwfScheme.setId(schemeId);
            newXjrNwfScheme.setSchemeInfoId(schemeInfoId);
            newXjrNwfScheme.setContent(xml);
            newXjrNwfScheme.setFjson(json);
            // 流程模板的新增失敗,抛出异常
            if (!nwfSchemeService.save(newXjrNwfScheme)) {
                log.info("流程模板的新增失败!");
                throw new Exception("流程模板的新增失败!");
            }
            // 流程模板信息的新增
            xjrNwfSchemeinfo.setId(schemeInfoId);
            xjrNwfSchemeinfo.setDeploymentId(deployId);
            xjrNwfSchemeinfo.setSchemeId(schemeId);
            xjrNwfSchemeinfo.setModelId(modelId);
            // 流程模板信息的新增失败，抛出异常
            if (baseMapper.insert(xjrNwfSchemeinfo) < 0) {
                log.info("流程模板信息的新增失败!");
                throw new Exception("流程模板信息的新增失败!");
            }
            ArrayList<XjrBaseTempfield> xjrBaseTempfields = new ArrayList<>();
            //保存流程json
            XjrBaseTempfield jsonXjrBaseTempfield = new XjrBaseTempfield();
            jsonXjrBaseTempfield.setType("30");
            jsonXjrBaseTempfield.setFkey(schemeInfoId+StringPool.UNDERSCORE+deployId);
            jsonXjrBaseTempfield.setFvalue(json);
            xjrBaseTempfields.add(jsonXjrBaseTempfield);
            //保存流程xml
            XjrBaseTempfield xmlXjrBaseTempfield = new XjrBaseTempfield();
            xmlXjrBaseTempfield.setType("31");
            xmlXjrBaseTempfield.setFkey(schemeInfoId+StringPool.UNDERSCORE+deployId);
            xmlXjrBaseTempfield.setFvalue(xml);
            xjrBaseTempfields.add(xmlXjrBaseTempfield);
            boolean save = tempfieldService.saveBatch(xjrBaseTempfields);
            //新增专项菜单
            if (menu.getInteger("isOpen") == 1) {
                ModuleDto moduleDto = new ModuleDto();
                moduleDto.setEnCode(menu.getString("F_EnCode"));
                moduleDto.setIcon(menu.getString("F_Icon"));
                moduleDto.setEnabledMark(menu.getInteger("isOpen"));
                moduleDto.setFullName(menu.getString("F_FullName"));
                moduleDto.setLgMarkCode(menu.getString("F_LgMarkCode"));
                moduleDto.setSubSystemId(menu.getString("F_SubSystemId"));
                moduleDto.setSortCode(menu.getInteger("F_SortCode"));
                moduleDto.setParentId(menu.getString("F_ParentId"));
                moduleDto.setDescription(menu.getString("F_Des"));
                NwfRelationDto nwfRelationDto = new NwfRelationDto();
                nwfRelationDto.setXjrBaseModule(moduleDto);
                XjrNwfRelationDto xjrNwfRelationDto = new XjrNwfRelationDto();
                xjrNwfRelationDto.setNwfRelationCode(menu.getString("F_EnCode"));
                xjrNwfRelationDto.setNwfRelationName(menu.getString("F_FullName"));
                JSONObject settingJson = new JSONObject();
                JSONArray step2 = new JSONArray();
                NwfSchemeInfoVo nwfSchemeInfoVo = baseMapper.selectNwfSchemeInByIds(Arrays.asList(schemeInfoId));
                step2.add(JSON.toJSON(nwfSchemeInfoVo));
                JSONObject step3 = new JSONObject();
                step3.put("userType", 1);
                step3.put("authorityData", new JSONArray());
                settingJson.put("step2", step2);
                settingJson.put("step3", step3);
                xjrNwfRelationDto.setSettingJson(JSON.toJSONString(settingJson));
                nwfRelationDto.setXjrNwfRelation(xjrNwfRelationDto);
                 String nwfRelationId = nwfRelationService.addNwfRelation(nwfRelationDto, SecureUtil.getUser());
                //保存流程和专项菜单关联
                XjrBaseTempfield xjrBaseTempfield = new XjrBaseTempfield();
                xjrBaseTempfield.setFkey(schemeInfoId);
                xjrBaseTempfield.setFvalue(nwfRelationId);
                xjrBaseTempfield.setType("29");
                tempfieldService.save(xjrBaseTempfield);
            }
            JsonUtil.bindFormAndFlow(json, schemeInfoId);
            // xjr_nwf_schemeauth流程权限列表新增
            nwfSchemeAuthService.saveAuthList(schemeInfoId, jsonArray);
            // 保存节点相关信息
            //是否为下一节点选定审批
            JsonUtil.saveNodeInfo( JSONObject.parseObject(json).getJSONArray("childShapes"), version, schemeInfoId);
        } else {
            log.info("流程部署失败!");
            throw new Exception(deployId);
        }
        return schemeInfoId;
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/10/27
     * @Param:[paramsMap, list]
     * @return:boolean
     * @Description:更新流程模板设计
     */
    @Transactional
    @Override
    public boolean updateProcess(NwfSchemeInfoDto dto, XjrUser currentUser) throws Exception {
        // 流程设计权限
        JSONArray jsonArray = JSON.parseArray(dto.getSchemeAuthList());
        // 流程图xml
        String xml = dto.getXml();
        // 流程配置Json
        String json = dto.getJson();
        // 流程任务命名规则
        String ruleName = dto.getRuleName();
        // 关联流程任务配置
        JSONObject associatedTasks = dto.getAssociatedTasks();
        // 流程超时设置
        JSONObject timeoutToRemind = dto.getTimeoutToRemind();
        // 流程关联菜单
        JSONObject menu = dto.getMenu();
        // 流程模板实体类
        XjrNwfSchemeinfo xjrNwfSchemeinfo = BeanUtil.copy(dto, XjrNwfSchemeinfo.class);
        // 模板ID
        String modelId = xjrNwfSchemeinfo.getModelId();
        // XjrNwfScheme和XjrNwfSchemeinfo对象
        String nwfSchemeinfoFId = xjrNwfSchemeinfo.getId();
        JSONObject obj = JSONObject.parseObject(json);
        JSONArray childShapes = obj.getJSONArray("childShapes");
        if(CollectionUtil.isEmpty(childShapes)){
            throw new Exception("请添加节点事件");
        }
        boolean bind = JsonUtil.isBind(json, nwfSchemeinfoFId);
        if (!bind) {
            throw new Exception("改表单已绑定其他流程,请重新选择其他表单!!");
        }
        XjrNwfScheme xjrNwfScheme = nwfSchemeService.getBySchemeInfoId(nwfSchemeinfoFId);
        // 会签节点的字符串处理
        String newJson = JsonUtil.processJsonHandle(json, nwfSchemeinfoFId);
        // 保存模板
        String deployId = FlowableUtil.deployByJson(modelId, newJson, xjrNwfSchemeinfo.getName(), currentUser.getUserId());
        // 获取版本号
        String version = FlowableUtil.getVersionByDepId(deployId);
        // 流程模板的修改
        xjrNwfScheme.setContent(xml);
        xjrNwfScheme.setFjson(json);
        // 流程模板的更新失敗,抛出异常
        if (!nwfSchemeService.updateById(xjrNwfScheme)) {
            log.info("流程模板更新失败!");
            throw new Exception("流程模板更新失败!");
        }
        // 流程模板信息的更新
        xjrNwfSchemeinfo.setSchemeId(xjrNwfScheme.getId());
        xjrNwfSchemeinfo.setDeploymentId(deployId);
        xjrNwfSchemeinfo.setModelId(modelId);
        if (baseMapper.updateById(xjrNwfSchemeinfo) < 0) {
            log.info("流程模板信息的更新失败!");
            throw new Exception("流程模板信息的更新失败!");
        }
        List<XjrBaseTempfield> xjrBaseTempfields = new ArrayList<>();
        //保存流程json
        XjrBaseTempfield jsonXjrBaseTempfield = new XjrBaseTempfield();
        jsonXjrBaseTempfield.setType("30");
        jsonXjrBaseTempfield.setFkey(nwfSchemeinfoFId+StringPool.UNDERSCORE+deployId);
        jsonXjrBaseTempfield.setFvalue(json);
        xjrBaseTempfields.add(jsonXjrBaseTempfield);
        //保存流程xml
        XjrBaseTempfield xmlXjrBaseTempfield = new XjrBaseTempfield();
        xmlXjrBaseTempfield.setType("31");
        xmlXjrBaseTempfield.setFkey(nwfSchemeinfoFId+StringPool.UNDERSCORE+deployId);
        xmlXjrBaseTempfield.setFvalue(xml);
        xjrBaseTempfields.add(xmlXjrBaseTempfield);
        boolean save = tempfieldService.saveBatch(xjrBaseTempfields);
        XjrBaseTempfield xjrBaseTempfield = tempfieldService.getByIdAndType(nwfSchemeinfoFId, "29");
        Integer isOpen = menu.getInteger("isOpen");
        // 编辑专项菜单
        if (xjrBaseTempfield != null) {
            XjrNwfRelation xjrNwfRelation = nwfRelationService.getById(xjrBaseTempfield.getFvalue());
            String moduleId = xjrNwfRelation.getModuleId();
            XjrBaseModule xjrBaseModule = baseModuleService.getById(moduleId);
            if (xjrBaseModule != null) {
                xjrBaseModule.setEnabledMark(isOpen);
                xjrBaseModule.setEnCode(menu.getString("F_EnCode"));
                xjrBaseModule.setIcon(menu.getString("F_Icon"));
                xjrBaseModule.setFullName(menu.getString("F_FullName"));
                xjrBaseModule.setLgMarkCode(menu.getString("F_LgMarkCode"));
                xjrBaseModule.setSubSystemId(menu.getString("F_SubSystemId"));
                xjrBaseModule.setSortCode(menu.getInteger("F_SortCode"));
                xjrBaseModule.setParentId(menu.getString("F_ParentId"));
                xjrBaseModule.setDescription(menu.getString("F_Des"));
                xjrNwfRelation.setNwfRelationCode(menu.getString("F_EnCode"));
                xjrNwfRelation.setNwfRelationName(menu.getString("F_FullName"));
                baseModuleService.updateById(xjrBaseModule);
                nwfRelationService.updateById(xjrNwfRelation);
            }
        } else if (xjrBaseTempfield == null && isOpen == 1) {
            //新增专项菜单
            ModuleDto moduleDto = new ModuleDto();
            moduleDto.setEnCode(menu.getString("F_EnCode"));
            moduleDto.setIcon(menu.getString("F_Icon"));
            moduleDto.setEnabledMark(menu.getInteger("isOpen"));
            moduleDto.setFullName(menu.getString("F_FullName"));
            moduleDto.setLgMarkCode(menu.getString("F_LgMarkCode"));
            moduleDto.setSubSystemId(menu.getString("F_SubSystemId"));
            moduleDto.setSortCode(menu.getInteger("F_SortCode"));
            moduleDto.setParentId(menu.getString("F_ParentId"));
            moduleDto.setDescription(menu.getString("F_Des"));
            NwfRelationDto nwfRelationDto = new NwfRelationDto();
            nwfRelationDto.setXjrBaseModule(moduleDto);
            XjrNwfRelationDto xjrNwfRelationDto = new XjrNwfRelationDto();
            xjrNwfRelationDto.setNwfRelationCode(menu.getString("F_EnCode"));
            xjrNwfRelationDto.setNwfRelationName(menu.getString("F_FullName"));
            JSONObject settingJson = new JSONObject();
            JSONArray step2 = new JSONArray();
            NwfSchemeInfoVo nwfSchemeInfoVo = baseMapper.selectNwfSchemeInByIds(Arrays.asList(nwfSchemeinfoFId));
            step2.add(JSON.toJSON(nwfSchemeInfoVo));
            JSONObject step3 = new JSONObject();
            step3.put("userType", 1);
            step3.put("authorityData", new JSONArray());
            settingJson.put("step2", step2);
            settingJson.put("step3", step3);
            xjrNwfRelationDto.setSettingJson(JSON.toJSONString(settingJson));
            nwfRelationDto.setXjrNwfRelation(xjrNwfRelationDto);
            String nwfRelationId = nwfRelationService.addNwfRelation(nwfRelationDto, SecureUtil.getUser());
            //保存流程和专项菜单关联
             xjrBaseTempfield = new XjrBaseTempfield();
            xjrBaseTempfield.setFkey(nwfSchemeinfoFId);
            xjrBaseTempfield.setFvalue(nwfRelationId);
            xjrBaseTempfield.setType("29");
            tempfieldService.save(xjrBaseTempfield);
        }
        JsonUtil.bindFormAndFlow(json, nwfSchemeinfoFId);
        // xjr_nwf_schemeauth流程权限列表新增
        nwfSchemeAuthService.saveAuthList(nwfSchemeinfoFId, jsonArray);
        // 保存按钮信息
        JsonUtil.saveNodeInfo(JSONObject.parseObject(json).getJSONArray("childShapes"), version, nwfSchemeinfoFId);
        return true;
    }

    @Override
    public boolean updateDeploymentId(String fId, String deploymentId) {
        XjrNwfSchemeinfo xjrNwfSchemeinfo = getById(fId);
        Optional.ofNullable(xjrNwfSchemeinfo)
                .ifPresent(nwfSchemeinfo -> {
                    nwfSchemeinfo.setDeploymentId(deploymentId);
                    updateById(nwfSchemeinfo);
                });
        return true;
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2020/11/25
     * @Param:[id]
     * @return:boolean
     * @Description:删除流程相关信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProcess(String id) throws Exception {
        XjrNwfSchemeinfo xjrNwfSchemeinfo = getById(id);
        // 流程模板信息的删除
        if (xjrNwfSchemeinfo != null) {
            String nwfSchemeinfoId = xjrNwfSchemeinfo.getId();
            ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(xjrNwfSchemeinfo.getDeploymentId()).singleResult();
            if(definition!=null) {
                List<Deployment> deploymentList = repositoryService.createDeploymentQuery().processDefinitionKey(definition.getKey()).list();
                List<String> deploymentIds = deploymentList.stream().map(s -> s.getId()).collect(Collectors.toList());
                // 删除流程在tempkeyvalue表中的数据
                tempfieldService.deleteByNwfInfoIdOrDeplId(nwfSchemeinfoId, deploymentIds);
                // 删除流程定义
                if (CollectionUtil.isNotEmpty(deploymentIds)) {
                    for (String deploymentId : deploymentIds) {
                        FlowableUtil.deleteProcessDefi(deploymentId);
                    }
                }
            }
            // 删除流程模板
            FlowableUtil.deleteModel(xjrNwfSchemeinfo.getModelId());
            // 流程模板删除
            if (baseMapper.deleteById(nwfSchemeinfoId) > 0) {
                XjrNwfScheme xjrNwfScheme = nwfSchemeService.getBySchemeInfoId(nwfSchemeinfoId);
                if (nwfSchemeService.removeById(xjrNwfScheme.getId())) {
                    // 流程模板权限的删除
                    nwfSchemeAuthService.delete(nwfSchemeinfoId);
                    //删除专项菜单关联
                    XjrBaseTempfield xjrBaseTempfield = tempfieldService.getByIdAndType(nwfSchemeinfoId, "29");
                    if(xjrBaseTempfield!=null) {
                        String nwfRelationId = xjrBaseTempfield.getFvalue();
                        nwfRelationService.deleteNwfRelation(nwfRelationId);
                    }
                    //更新绑定绑定流程的表单
                    XjrFormSchemeInfo xjrFormSchemeInfo = xjrFormSchemeInfoService.getOne(Wrappers.<XjrFormSchemeInfo>query().lambda().eq(XjrFormSchemeInfo::getNwfSchemeinfoId, id));
                    if (xjrFormSchemeInfo != null) {
                        xjrFormSchemeInfo.setNwfSchemeinfoId(null);
                        xjrFormSchemeInfoService.updateById(xjrFormSchemeInfo);
                    }
                    return;
                }
            }
        }
        throw new Exception("删除流程失败!");
    }

    @Override
    public File exportGeneralProcess(String id, Integer type) {
        String content = "";
        String imgPath = IoUtil.getProjectPath() + "static" + StringPool.SLASH + "images" + StringPool.SLASH + "flowableFile"
                + StringPool.SLASH + IdWorker.get32UUID() + StringPool.DOT + "txt";
        ;
        File file = new File(imgPath);
        StringBuffer stringBuffer = new StringBuffer();
        XjrNwfScheme xjrNwfScheme = nwfSchemeService.getBySchemeInfoId(id);
        if (xjrNwfScheme != null) {
            String json = xjrNwfScheme.getFjson();
            String xml = xjrNwfScheme.getContent();
            if (type == 0) {
                // 通用流程(xml)
                content = stringBuffer.append(json).append(StringPool.NEWLINE).append("@XJR@").append(StringPool.NEWLINE).append(xml).toString();
            } else {
                // 流程(json + xml)
                content = xml;
            }
            return FileUtil.writeString(content, file, "UTF-8");
        }
        return file;
    }

    /**
     * @Author:湘北智造-框架开发组
     * @Date:2021/3/8
     * @Param:[file]
     * @return:java.lang.String
     * @Description:导入流程(json)
     */
    @Override
    public String importProcess(MultipartFile multipartFile) throws IOException {
        File file = IoUtil.toFile(multipartFile);
        return FileUtil.readString(file,"UTF-8");
    }
}
